﻿using System;

namespace Billing2
{
    public class LockUnlock
    {
        public int DoLockUnlock(bool isLock, int BillPeriodID, int OrganizationID, int SiteID, int CostCentreID)
        {
            int? nCC = Common.db.SelectInt(@"
                SELECT COUNT(*)
                FROM BillReportRepository
                WHERE BillPeriodID = @BillPeriodID
                    AND CostCentreID = @CostCentreID
                    AND Locked = @Locked
                ", Convert.ToInt64(BillPeriodID)
                , Convert.ToInt64(CostCentreID)
                , (isLock ? 0 : 1));

            int? nOrg = Common.db.SelectInt(@"
                SELECT COUNT(*)
                FROM BillReportRepository
                WHERE BillPeriodID = @BillPeriodID
                    AND SiteID = 0
                    AND CostCentreID = 0
                    AND Locked = @Locked
                ", Convert.ToInt64(BillPeriodID)
                , (isLock ? 0 : 1));

            int n = nCC.Value + nOrg.Value;

            Common.db.Exec(@"
                UPDATE BillReportRepository
                SET Locked = @Locked
                WHERE BillPeriodID = @BillPeriodID
                    AND CostCentreID = @CostCentreID
                ", (isLock ? 1 : 0)
                , Convert.ToInt64(BillPeriodID)
                , Convert.ToInt64(CostCentreID));

            Common.db.Exec(@"
                UPDATE BillReportRepository
                SET Locked = @Locked
                WHERE BillPeriodID = @BillPeriodID
                    AND SiteID = 0
                    AND CostCentreID = 0
                ", (isLock ? 1 : 0)
                , Convert.ToInt64(BillPeriodID));

            string year = Common.db.BillPeriod.selectPK2(BillPeriodID).Year0;
            string month = Common.db.BillPeriod.selectPK2(BillPeriodID).Month0;

            string OrganizationName = Common.db.Organization.selectPK2(Convert.ToInt32(OrganizationID)).OrgIDName;
            string SiteName = Common.db.SitesInOrganization.selectPK2(Convert.ToInt32(SiteID)).SiteIDName;
            string CostCentreName = Common.db.CostCentresInSite.selectPK2(Convert.ToInt32(CostCentreID)).CostCentreIDName;
            Common.AuditLog(String.Format("{0} {1} billing report(s). Period={2}-{3} Organization={4} Site={5} CostCentre={6}"
                , (isLock ? "lock" : "unlock"), n, month, year
                , OrganizationName, SiteName, CostCentreName));

            return n;
        }
    }
}